<template>
  <info-page-container @goListPage="cancel">
    <div class="info-data-container full-container flex-column">


      <div class="info-base-data">
        <el-button class="diy-bt txt-bt" icon="el-icon-plus" size="mini" @click="drawDisaster">
          绘制受灾面
        </el-button>
        <el-button v-if="bufferGeometry != null" class="diy-bt txt-bt" icon="el-icon-plus" size="mini"
                   @click="clearDraw">
          清除绘制
        </el-button>
        <el-form :rules="rules" :model="formData" ref="baseForm" size="small"
                 label-width="80px">
          <div class="flex-row form-item-parent">
            <el-form-item class="column-item half-item" label="档案名称" prop="disasterArchiveName">
              <el-input
                v-model="formData.disasterArchiveName"
                placeholder="请输入档案名称"
                clearable
              >
              </el-input>
            </el-form-item>
            <el-form-item class="column-item half-item" label="档案编号" prop="disasterArchiveNo">
              <el-input
                v-model="formData.disasterArchiveNo"
                placeholder="请输入档案编号"
                clearable
              >
              </el-input>
            </el-form-item>
          </div>
          <div class="flex-row form-item-parent">
            <el-form-item class="column-item half-item" label="受灾时间" prop="disasterDate">
              <el-date-picker
                v-model="formData.disasterDate"
                value-format="yyyy-MM-dd"
                @change="initDisasterChitLayer"
              ></el-date-picker>
            </el-form-item>
            <el-form-item class="column-item half-item" label="涉及险种" prop="disasterInsuranceTypeIds">
              <el-select @change="initDisasterChitLayer" multiple v-model="formData.disasterInsuranceTypeIds"
                         placeholder="请选择险种">
                <el-option
                  v-for="item in insuranceList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </div>

        </el-form>
      </div>

      <div class="list-container">
        <layout-container title="涉及保单列表">
          <template slot="title">
            <div class="flex-row">
              <div class="important-txt">
                受灾总面积：{{ formData.disasterArea }} 亩
              </div>
              <div class="important-txt" style="margin-left: 20px">
                理论赔付额：{{ formData.disasterCompensation }} 元
              </div>
            </div>
          </template>
          <template>
            <el-table
              class="diy-table"
              :data="disasterDataList"
              style="width: 100%;" height="100%">
              <el-table-column
                prop="orderNo"
                label="保单编号">
              </el-table-column>
              <el-table-column
                prop="orderName"
                label="保单名称">
              </el-table-column>
              <el-table-column
                prop="typeName"
                label="承保险种">
              </el-table-column>
              <el-table-column
                prop="sumArea"
                label="涉及面积（亩）">
                <template slot-scope="scope">
                    <span class="important-txt">
                    {{ scope.row.sumArea }}
                    </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="sumArea"
                label="涉及农户数量（户）">
                <template slot-scope="scope">
                    <span class="important-txt">
                    {{ scope.row.archives.length }}户
                    </span>
                </template>
              </el-table-column>
              <el-table-column
                prop="sumMoney"
                label="理论赔付额(元)">
                <template slot-scope="scope">
                    <span class="important-txt">
                    {{ scope.row.sumMoney }}
                    </span>
                </template>
              </el-table-column>

              <el-table-column width="170" label="操作" align="center">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="locationByData(disasterChitLayerId,scope.row,'档案信息')"
                  >定位
                  </el-button>
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="addFarmer(scope.row)"
                  >详情
                  </el-button>
                </template>
              </el-table-column>

            </el-table>
          </template>
        </layout-container>
      </div>

      <div class="handle-bt-container flex-row">
        <el-button class="diy-bt" icon="el-icon-refresh" size="mini" @click="save">保存</el-button>
        <el-button class="diy-bt" icon="el-icon-refresh" size="mini" @click="cancel">取消</el-button>
      </div>

    </div>
  </info-page-container>
</template>

<script>
import {infoPageMixins} from "@/views/business/mixins/infoPageMixins";
import {pageBaseMapMixins} from "@/views/business/mixins/pageBaseMapMixins";
import {GEOMETRY_TYPE, HANDLE_TYPE, REFRESH_PAGE_TYPE} from "@/views/business/constantData";
import {addInsurance, getInsuranceInfo, updateInsurance} from "@/api/business/underwritingFile";
import {getDataAdminList} from "@/api/business/dataAdministration";
import {isArr} from "@/utils/arrayUtil";
import {union} from 'lark-map'
import {addDisaster, getDisasterInfo, queryAllDisasterData, updateDisaster} from "@/api/business/disasterFile";

export default {
  mixins: [infoPageMixins, pageBaseMapMixins],
  data() {
    return {
      chitLayerId: 'chit',
      disasterLayerId: 'disasterLayer',
      disasterChitLayerId: 'disasterChitLayer',
      formData: {
        disasterArchiveName: null,
        disasterArchiveNo: null,
        disasterInsuranceTypeIds: [],
        disasterDate: null,
        disasterArea: 0,
        disasterGeo: null,
        disasterCompensation: 0,
      },
      bufferGeometry: null,
      disasterDataList: [],
      insuranceList: [],
      rules: {
        disasterArchiveName: [
          {required: true, message: '档案名称不能为空', trigger: 'blur'},
        ],
        disasterArchiveNo: [
          {required: true, message: '档案编号不能为空', trigger: 'change'},
        ],
        disasterDate: [
          {required: true, message: '受灾时间不能为空', trigger: 'change'},
        ],
        disasterInsuranceTypeIds: [
          {required: true, message: '涉及险种不能为空', trigger: 'change'},
        ],
      },
    };
  },
  methods: {
    async clearDraw() {
      this.bufferGeometry = null;
      this.formData.disasterGeo = null;
      await this.initDisasterChitLayer()
    },
    async drawDisaster() {
      let {formData: {disasterDate, disasterGeo, disasterInsuranceTypeIds}} = this

      this.$message({
        message: '请在左侧地图进行绘制',
        type: 'info'
      })
      const geometryType = GEOMETRY_TYPE.POLYGON;
      let graphic = await this.baseMap.drawGeometry(geometryType, true);
      let coincideFlag = await this.baseMap.checkCoincideByGraphic({layerId: this.disasterLayerId, graphic})
      if (coincideFlag) {
        this.$message.error(`受灾区域不能重合`);
        return
      }
      this.bufferGeometry = this.bufferGeometry != null ? union([this.bufferGeometry, graphic.geometry]) : graphic.geometry;
      let {rings} = this.bufferGeometry
      this.formData.disasterGeo = JSON.stringify(rings);
      await this.initDisasterChitLayer()
    },
    async initDisasterChitLayer() {
      let features = await this.getDisasterChit();
      this.setAreaToFeatures(features);
      this.setDisasterDataListByFeatures(features)
      await this.addDisasterChitLayer(features)
      this.formData.disasterArea = isArr(features) ? _.round(_.sum(this.disasterDataList.map(item => item.sumArea)), 2) : 0
      this.formData.disasterCompensation = isArr(features) ? _.round(_.sum(this.disasterDataList.map(item => item.sumMoney)), 2) : 0
    },
    async addDisasterChitLayer(features) {
      let owner = this
      this.removeLayer({layerId: owner.disasterChitLayerId})
      return new Promise(async (resolve, reject) => {
        if (!isArr(features)) {
          resolve()
          return
        }
        const geometryType = GEOMETRY_TYPE.POLYGON;
        await owner.addLayer({
          layerId: owner.disasterChitLayerId,
          source: features,
          rendererSymbol: {
            type: "simple-fill",
            color: [255, 255, 0, 0.1],
            outline: {
              color: [255, 255, 0, 1],
              width: 2
            }
          },
          geometryType,
          txtFileList: [
            {
              value: 'orderName',
              label: '保单名称',
              addToMap: false,
            },
            {
              value: 'orderNo',
              label: '保单编号',
              addToMap: false,
            },
            {
              value: 'typeName',
              label: '险种名称',
              addToMap: false,
            },
            {
              value: 'typeNo',
              label: '险种编号',
              addToMap: false,
            },
            {
              value: 'startTime',
              label: '保险生效时间',
              addToMap: false,
            },
            {
              value: 'endTime',
              label: '保险失效时间',
              addToMap: false,
            },
            {
              value: 'farmerIdentity',
              label: '农户身份证',
              addToMap: false,
            },
            {
              value: 'farmerName',
              label: '农户名称',
              addToMap: false,
            },
            {
              value: 'plotNo',
              label: '地块编号',
              addToMap: false,
            },
            {
              value: 'geometryArea',
              label: '面积(亩)',
              suffix: ' 亩',
              addToMap: false,
            },
            {
              value: 'money',
              label: '理赔款(元)',
              suffix: ' 元',
              addToMap: false,
            },
          ],
          txtColor: '#fff',
          fontSize: 15
        })
        resolve()
      })
    },
    setDisasterDataListByFeatures(features) {
      let owner = this
      this.disasterDataList = []
      if (!isArr(features)) return;
      features.forEach(feature => {
        feature.attributes.money = _.round(feature.attributes.unitIndemnity * feature.attributes.geometryArea, 2)
        let {
          attributes: {
            orderName,
            insuranceOrderId,
            orderNo,
            insuranceTypeId,
            typeName,
            typeNo,
            startTime,
            endTime,
            farmerId,
            farmerIdentity,
            farmerName,
            farmerNo,
            unitIndemnity,
            plotNo,
            geometryArea,
            compensateRatio,
            insureArea,
            insureMoney,
            money,
            plotArea,
            id,
            uid
          },
          geometry
        } = feature
        let currentOrderItem = owner.disasterDataList.find(item => item.insuranceOrderId == insuranceOrderId);
        if (!currentOrderItem) {
          currentOrderItem = {
            archives: [],
            compensateRatio,
            orderName,
            insuranceOrderId,
            orderNo,
            insuranceTypeId,
            typeName,
            typeNo,
          }
          owner.disasterDataList.push(currentOrderItem)
        }
        let currentFarmer = currentOrderItem.archives.find(item => item.farmerId == farmerId);
        if (!currentFarmer) {
          currentFarmer = {
            plots: [],
            compensateRatio,
            insureMoney,
            insureArea,
            endTime,
            startTime,
            farmerId,
            farmerIdentity,
            farmerName,
            farmerNo,
          }
          currentOrderItem.archives.push(currentFarmer)
        }
        let currentPlot = {plotArea, money, sumArea: geometryArea, plotNo, id, uid}
        currentFarmer.plots.push(currentPlot)
      })
      owner.disasterDataList.forEach(rowItem => {
        rowItem.sumMoney = _.round(_.sum(rowItem.archives.map(item => {
          item.sumMoney = _.round(_.sum(item.plots.map(plot => plot.money)), 2)
          return item.sumMoney
        })), 2)
        rowItem.sumArea = _.round(_.sum(rowItem.archives.map(item => {
          item.sumArea = _.round(_.sum(item.plots.map(plot => plot.sumArea)), 2)
          return item.sumArea
        })), 2)
      })
    },
    getDisasterChit() {
      return new Promise(async (resolve, reject) => {
        this.removeLayer({layerId: this.disasterLayerId})
        let {formData: {disasterDate, disasterGeo, disasterInsuranceTypeIds}} = this;
        if (disasterGeo == null || disasterGeo == '') {
          resolve([])
          return;
        }
        const geometryType = GEOMETRY_TYPE.POLYGON;
        let graphicList = [{geoData: disasterGeo}];
        await this.addLayerByGraphicData({
          layerId: this.disasterLayerId,
          rendererSymbol: {
            type: "simple-fill",
            color: [255, 0, 0, 0.1],
            outline: {
              color: [255, 0, 0, 1],
              width: 2
            }
          },
          graphicList,
          geometryType,
        })
        if (disasterDate == null || disasterDate == '' || !isArr(disasterInsuranceTypeIds)) {
          resolve([])
          return;
        }
        let disasterChitList = await this.getGraphicByGeometryAndWhere({layerId: this.disasterLayerId});
        let geometry = union(disasterChitList.map(item => item.geometry))
        let where = ''
        disasterInsuranceTypeIds.forEach((insuranceTypeId, index) => {
          where = index != 0 ? `${where} or insuranceTypeId = '${insuranceTypeId}'` : `insuranceTypeId = '${insuranceTypeId}'`
        })
        let currentDisasterChitList = await this.getCuttingGraphicByGeometryAndWhere({
          layerId: this.chitLayerId,
          where,
          geometry,
          cutting: true
        });
        currentDisasterChitList = currentDisasterChitList.filter(feature => {
          let {attributes: {startTime, endTime}} = feature
          startTime = new Date(startTime)
          endTime = new Date(endTime)
          let currentTime = new Date(disasterDate)
          return currentTime >= startTime && currentTime <= endTime
        })
        resolve(currentDisasterChitList)
      })
    },
    cancel() {
      this.removeFarmerLayer()
      this.goListPage(REFRESH_PAGE_TYPE.NO_REFRESH)
    },
    saveFinish() {
      this.removeFarmerLayer()
      this.goListPage(REFRESH_PAGE_TYPE.REFRESH)
    },
    removeFarmerLayer() {
      this.removeRender()
      // this.removeLayer({layerId: this.chitLayerId})
    },
    save() {
      let owner = this
      let {disasterDataList, formData: {disasterGeo}} = this
      this.$refs.baseForm.validate((valid) => {
        if (valid) {
          if (disasterGeo == null || disasterGeo == '') {
            this.$message({
              message: '请绘制受灾面',
              type: 'error'
            })
            return
          }
          owner.startLoading()
          let {formData, formData: {id}} = owner;
          const params = {...formData, disasterDataList}
          if (id == null || id == '') {
            addDisaster(params).then(res => {
              this.$message({
                message: '添加成功',
                type: 'info'
              })
            }).finally(() => {
              owner.endLoading()
              this.saveFinish()
            })
          } else {
            updateDisaster(params).then(res => {
              this.$message({
                message: '修改成功',
                type: 'info'
              })
            }).finally(() => {
              owner.endLoading()
              this.saveFinish()
            })
          }
        }
      });
    },
    async setCurrentItem(currentItem) {
      let owner = this
      if (currentItem != null && currentItem?.id != null && currentItem?.id !== '') {
        getDisasterInfo({id: currentItem.id}).then(async res => {
          let {
            data: {
              id,
              disasterArchiveName,
              disasterArchiveNo,
              disasterInsuranceTypeIds,
              disasterDate,
              disasterArea,
              disasterGeo,
              disasterCompensation
            }
          } = res;
          disasterInsuranceTypeIds = disasterInsuranceTypeIds.map(item => {
            item = item.toString()
            return item
          });
          owner.formData = {
            id,
            disasterArchiveName,
            disasterArchiveNo,
            disasterInsuranceTypeIds,
            disasterDate,
            disasterArea,
            disasterGeo,
            disasterCompensation
          }
          const geometryType = GEOMETRY_TYPE.POLYGON
          let featuresList = this.getFeaturesByGraphicList([{geoData: disasterGeo}], geometryType)
          this.bufferGeometry = featuresList[0].geometry
          await this.initDisasterChitLayer()
        })
      } else {
        owner.disasterDataList = [];
        owner.formData = {
          disasterArchiveName: null,
          disasterArchiveNo: null,
          disasterInsuranceTypeIds: [],
          disasterDate: null,
          disasterArea: 0,
          disasterGeo: null,
          disasterCompensation: 0,
        };
      }
    },
    addFarmer(farmerItem) {
      this.$emit('goInfoPage', farmerItem)
    },
    locationByData(layerId, row, popupTitle) {
      let {insuranceOrderId} = row
      const where = `insuranceOrderId = '${insuranceOrderId}'`
      this.locationByWhere({layerId, where, openPopupFlag: false, popupTitle})
    },
    getFeaturesByDisasterList(disasterList) {
      let graphicList = []
      disasterList.forEach(rowItem => {
        let {
          compensateRatio,
          orderName,
          insuranceOrderId,
          orderNo,
          insuranceTypeId,
          typeName,
          typeNo,
          archives
        } = rowItem
        archives.forEach(item => {
          let {endTime, startTime, farmerId, farmerIdentity, farmerName, farmerNo, money, plots} = item
          let sumArea = _.sum(plots.map(plotItem => parseFloat(plotItem.geometryArea)))
          let unitIndemnity = money / sumArea * compensateRatio
          plots.forEach(plotItem => {
            let {plotNo, geometryArea, geoData, id} = plotItem
            graphicList.push({
              attributes: {
                uid: `${insuranceOrderId}_${farmerId}_${id}`,
                orderName,
                insuranceOrderId,
                orderNo,
                insuranceTypeId: insuranceTypeId.toString(),
                typeName,
                typeNo,
                startTime,
                endTime,
                farmerId,
                farmerIdentity,
                farmerName,
                unitIndemnity,
                farmerNo,
                plotNo,
                id,
                compensateRatio,
                insureMoney: money,
                geometryArea,
                plotArea: geometryArea,
                insureArea: sumArea
              },
              geoData
            })
          })
        })
      })
      const txtFileList = [
        {
          value: 'orderName',
          label: '保单名称'
        },
        {
          value: 'insuranceOrderId',
          label: '保单id'
        },
        {
          value: 'orderNo',
          label: '保单编号'
        },
        {
          value: 'insuranceTypeId',
          label: '险种id'
        },
        {
          value: 'typeName',
          label: '险种名称'
        },
        {
          value: 'typeNo',
          label: '险种编号'
        },
        {
          value: 'startTime',
          label: '保险生效时间'
        },
        {
          value: 'endTime',
          label: '保险失效时间'
        },
        {
          value: 'farmerId',
          label: '农户id'
        },
        {
          value: 'farmerIdentity',
          label: '农户身份证'
        },
        {
          value: 'farmerName',
          label: '农户名称'
        },
        {
          value: 'unitIndemnity',
          label: '单位赔款',
          suffix: ' 元'
        },
        {
          value: 'plotNo',
          label: '地块编号',
          suffix: ' 元'
        },
      ];
      return {graphicList, txtFileList}
    },
    async addBaseLayer() {
      return new Promise(async (resolve, reject) => {
        let disasterList = await queryAllDisasterData()
        let {rows} = disasterList;
        const geometryType = GEOMETRY_TYPE.POLYGON;
        let {graphicList, txtFileList} = this.getFeaturesByDisasterList(rows)
        await this.addLayerByGraphicData({
          layerId: this.chitLayerId,
          rendererSymbol: {
            type: "simple-fill",
            color: [255, 255, 0, 0],
            outline: {
              color: [255, 255, 0, 0],
              width: 2
            }
          },
          graphicList,
          geometryType,
          txtFileList,
          txtColor: 'rgba(255,255,255,0)'
        })
        resolve()
      })
    },
    initMonitor() {
      // this.openMonitor({layerId: this.disasterLayerId, backFun: this.setCurrentFeature})
    },
    setCurrentFeature({point, layer, features}) {
      const popupTitle = '农户信息'
      this.locationByFeatures({layerId: layer.id, features, openPopupFlag: true, popupTitle, point})
    },
    setInsuranceList() {
      return new Promise((resolve, reject) => {
        getDataAdminList().then(res => {
          this.insuranceList = _.map(res.rows, item => {
            let {typeName: label, id: value} = item;
            return {label, value: value.toString()}
          })
          resolve()
        });
      })
    }
  },
  async created() {
    await this.awaitMapLoaded()
    await this.addBaseLayer()
    await this.setInsuranceList()
    this.setCurrentItem(this.currentItem)
  }
};
</script>

<style scoped lang="scss">
::v-deep .info-page-header {
  height: 4% !important;
}

.info-data-container {
  .info-base-data {
    height: 30% !important;
    max-height: 30% !important;
  }

  .list-container {
    height: 65% !important;
  }

  .handle-bt-container {
  }
}
</style>
